package com.deyuanyun.pic.pipe.util;

import com.deyuanyun.pic.common.spring.SpringAppliction;
import com.deyuanyun.pic.common.tool.Globals;
import com.deyuanyun.pic.common.util.StringUtils;
import com.deyuanyun.pic.common.util.ajax.AjaxResponse;
import com.deyuanyun.pic.common.util.web.DownLoadUtil;
import com.deyuanyun.pic.common.util.web.RequestResponseContext;
import com.deyuanyun.pic.settings.controller.dto.org.CompanyLogoVO;
import com.deyuanyun.pic.settings.service.org.CompanyService;
import org.apache.poi.ss.usermodel.Workbook;
import org.jeecgframework.poi.excel.ExcelExportUtil;
import org.jeecgframework.poi.excel.entity.TemplateExportParams;
import org.jeecgframework.poi.util.PoiMergeCellUtil;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * excel 导出
 *
 * @author scalpel.王敏
 * @version [v1.0] 创建时间（2016/11/10）
 * @see // 引用的类
 * Method List:
 * 1.----------------
 * 2.----------------
 * History:
 */
public class ExportExcel {


    /**
     * 封装参数
     *
     * @param param        将要压入excel的数据
     * @param response
     * @param excelName    excel 导出的名称
     * @param templateName 模板名称，用来获取excel的后缀
     * @throws IOException
     */
    private static void fitParam(Map param, HttpServletResponse response, String excelName, String templateName) throws IOException {




        CompanyService companyService = SpringAppliction.getBean(CompanyService.class);
        CompanyLogoVO companyLogoVO = companyService.getUserCompanyLogo();
        if (companyLogoVO == null || StringUtils.isEmpty(companyLogoVO.getLogoPath())) {
            companyLogoVO = new CompanyLogoVO();

            if(Globals.getProperties("logo") != null)
            {
                companyLogoVO.setLogoPath(getPath() + Globals.getProperties("logo"));
                companyLogoVO.setName(Globals.getProperties("companyName"));
            }else {
                companyLogoVO.setLogoPath(getPath() + "/template/logo.png");
                companyLogoVO.setName("四川德源云管道信息技术有限公司");
            }
        }

//        companyLogoVO = new CompanyLogoVO();
//        companyLogoVO.setLogoPath("/work/20161114145540.jpg");
//        companyLogoVO.setName("测试公司");
        param.put("logo", companyLogoVO.getLogoPath());
        param.put("companyName", companyLogoVO.getName());
        param.put("sysDate", com.deyuanyun.pic.common.util.StringUtils.convertDateToString(new Date(), "yyyy-MM-dd"));



    }


    /**
     * @param templateName 模板名称
     * @param param        压入excel的数据
     * @param response
     * @param excelName    导出文件名称
     * @throws IOException
     */
    public final static void exportExcel(String templateName, Map param, HttpServletResponse response, String excelName) throws IOException {
        HttpServletRequest request = RequestResponseContext.getRequest();
        StringBuffer name = new StringBuffer();
        String lineName = request.getParameter("lineName");
        String taskName = request.getParameter("taskName");
        String apprarse = request.getParameter("apprarse");
        String fileName = request.getParameter("fileName");
        if (StringUtils.isEmpty(fileName)) {
            fileName = excelName;
        }
        param.put("fileName", fileName);


        if (null != lineName) {
            name.append(lineName);
        }
        if (null != taskName) {
            name.append(taskName);
        }
        name.append(excelName);
        if (null != apprarse) {
            name.append(apprarse);
        }
        name.append(com.deyuanyun.pic.common.util.StringUtils.convertDateToString(new Date(), "yyyyMMdd"));


        excelName = name + templateName.substring(templateName.lastIndexOf("."));

        String userAgent = request.getHeader("User-Agent");
        try {
            excelName = DownLoadUtil.encodeDownloadName(excelName, userAgent);
        } catch (Exception e) {
            excelName = "fileName";
        }

        response.setHeader("Content-disposition", "attachment; filename=" + excelName);

        List list = (List) param.get("data");//目前内检测就是这样玩的
        List list2 = (List) param.get("data2");//有第二个工作簿
        if ((list == null || list.size() == 0) && (list2 == null || list2.size() == 0)) {
            response.setHeader("Content-Disposition", "");
            AjaxResponse.sendText(response, "<script>alert('数据为空，不可进行下载操作!');window.close();</script>");
            return ;
        }
        Workbook workbook = createWorkBook(templateName,param,response,excelName);
        workbook.write(response.getOutputStream());
        workbook.close();
    }



    /**
     * @param templateName 模板名称
     * @param param        压入excel的数据
     * @param response
     * @param excelName    导出文件名称
     * @throws IOException
     */
    public final static Workbook exportExcelReturnWrokBook(String templateName, Map param, HttpServletResponse response, String excelName) throws IOException {

        Workbook workbook = createWorkBook(templateName,param,response,excelName);
       return workbook;
    }

    private  static  final  Workbook createWorkBook(String templateName, Map param, HttpServletResponse response, String excelName)  throws IOException
    {


        fitParam(param, response, excelName, templateName);

        TemplateExportParams params = new TemplateExportParams(templateName);
        //两个工作簿
        if (param.get("data2") != null && param.get("data") != null) {
            params.setSheetNum(new Integer[]{0, 1});
        }

        if (param.get("data2") != null && param.get("data") == null) {
            params.setSheetNum(new Integer[]{1});
        }


        Workbook workbook = ExcelExportUtil.exportExcel(params, param);
        //PoiMergeCellUtil.mergeCells(workbook.getSheetAt(0), 1, 30);

        if (param.get("data2") != null) {
            //PoiMergeCellUtil.mergeCells(workbook.getSheetAt(1), 1, 30);
        }
        return workbook;
    }


    public static String getPath()
    {
        String path = ExportExcel.class.getResource("/").getPath();
        if(path.indexOf(":") == 2)
        {
            path = path.substring(1);
        }
        return path;
    }

    public final  static  void getPathExportExcel(String templateName,Map param,HttpServletResponse response,String excelName) throws IOException {
        String path = "";
        if(templateName.indexOf("classes") == -1) {
            path = ExportExcel.class.getResource("/").getPath();
            if(path.indexOf(":") == 2)
            {
                path = path.substring(1);
                path = path.substring(0,path.length()-1);
            }
        }
        ExportExcel.exportExcel(path + templateName,param,response,excelName);
    }
    public final  static  Workbook exportExcelToZip(String templateName,Map param,HttpServletResponse response,String excelName) throws IOException {
        String path = ExportExcel.class.getResource("/").getPath();
        if(path.indexOf(":") == 2)
        {
            path = path.substring(1);
        }

        return  ExportExcel.exportExcelReturnWrokBook(path + templateName,param,response,excelName);
    }

}
